<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Guarantee extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
    $this->load->library('encrypt');
    $this->load->library('enc');
    $this->load->library('session');
    $this->load->model('mglobal');
    $this->load->model('mmaster');
    $this->load->library('form_validation');
    $this->load->model('mguarantee');
  }

  public function index()
  {
    $template = "shell/smooth";
    $data["main_view"] = "f-grid-guarantee";
    $this->load->view($template, $data, FALSE);
  }

  function read()
  {
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata("username"));
    
    $result = $this->mguarantee->get_all_guarantee($cluster_id);

    //penambahan nomor statis untuk grid SSP
    $start=$_GET['iDisplayStart'];
    $result['iDisplayStart']=$start;
    echo json_encode($result);
  }

  public function create()
  {
    $template = "shell/smooth";
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata("username"));
    $data["main_view"] = "f-guarantee";
    $data["territory"] = $this->mglobal->getTerritoryPath();
    $data["program"] = $this->mguarantee->program();
    $territory = explode(' > ', $data["territory"]);
    if (!$territory[1])
    {
      $this->session->set_flashdata('message', 'Pilih cluster terlebih dahulu');
      redirect('index.php/cluster');
    }
    $data["sales"] = $this->mglobal->get_sales($cluster_id, array(8,9,31) );

    // print_r($data);die();
      // $this->save();

    $this->load->view($template, $data, FALSE);
  }

  public function save()
  {    
    $user_id = explode(';',$this->input->post("sales_id"));
    $data["user_id"] = $user_id[0];
    $data["channel_id"] = trim($this->input->post("partner_id"));
    $data["requestor"] = intval($this->input->post("frontliner_id"));
    $data["claim_date"] = $this->input->post("tanggal");
    $data["program"] = $this->input->post("program_id");
    $iccid = $this->input->post("iccid");

    $this->form_validation->set_rules('sales_id', 'Sales Person', 'required');
    $this->form_validation->set_rules('partner_id', 'ID Partner', 'trim|required');
    $this->form_validation->set_rules('program_id', 'Program', 'required');
    $this->form_validation->set_rules('iccid[]', 'ICCID', 'trim|required');

    $dup_iccid = array(); $new_iccid = array();
    if ($this->form_validation->run() != false) {
      $duplicate_iccid = array_count_values($iccid);    // Returns ['iccid_0']=>counts, [iccid_1]=>counts
      $unique_iccid = array_unique($iccid);             // Returns [0]=>"iccid_0", [1]=>"iccid_1"
      $duplicate_iccid; $unique_iccid; 
      foreach ($unique_iccid as $key) {     // $key become unique_iccid value: iccid_0, iccid_1
        if($duplicate_iccid[$key] == 1) {   // if the count equal to 1, create new array, the array is now unique
          $new_iccid[] = trim($key);
        }
        else {
          $dup_iccid[] = $key;              // if the count greater then to 1, create new array contains unique iccid above.
        }
      }

      $iccidsama='';
      foreach ($dup_iccid as $a){
        $iccidsama.=$a.', ';
      }
      $valid_iccid = array();
      // Validate each unique iccids and return as new array named valid_iccid (batch mode way faster)
      if(count($new_iccid) > 0 ) {
        $valid_iccid = $this->_validate_item_level2($data["user_id"], $data["channel_id"], $new_iccid);
      }
      // mainstream way is to mainstream
      // foreach ($new_iccid as $key) { 
      //   $temp = $this->_validate_item_level2($data["user_id"], $data["channel_id"], trim($key)); 
      //   if ($temp['istatus'] != 'invalid')
      //     {$valid_iccid[] = $key;}
      // }

      // var_dump($valid_iccid);
      // die();
      if(count($valid_iccid))
      {
        $this->db->trans_begin();
        $claim_id = $this->mguarantee->save($data);

        // nanti valid iccid akan kita simpan dengan insert_batch
        // jadi kita tambahin dulu field yang penting (claim_id dan istatus)
        $valid_item = array();
        
        for ($i=0; $i < count($valid_iccid); $i++) { 
          $valid_item[$i]["claim_id"] = $claim_id;
          $valid_item[$i]["istatus"] = 1;
          $valid_item[$i]["iccid"] = $valid_iccid[$i];
        }
        // print_r($valid_item); die();
        // tell me if you have a better idea than above

        $this->mguarantee->save_detail($valid_item, $claim_id);
        if ($this->db->trans_status() === FALSE)
          { 
            $this->db->trans_rollback(); 
            $this->session->set_flashdata('message', 'Klaim gagal disimpan');
            $this->session->set_flashdata('div_class', 'error');
            redirect(base_url().'index.php/guarantee');
          }
        else
          { 
            $this->db->trans_commit(); 
            if (count($dup_iccid) != 0) { $message = count($valid_iccid)." item berhasil disimpan dengan nomor transaksi $claim_id, terdapat duplikat ICCID: $iccidsama" ; }
            else {$message = count($valid_iccid)." item berhasil disimpan dengan nomor transaksi " . $claim_id; }
            $this->session->set_flashdata('message', $message);
            $this->session->set_flashdata('div_class', 'success');
            redirect(base_url().'index.php/guarantee');
          }
      }
      else
      {
        $this->session->set_flashdata('message', 'Semua item tidak valid/sudah pernah di klaim sebelumnya');
        $this->session->set_flashdata('div_class', 'error');
        redirect(base_url().'index.php/guarantee');
      }

    }


  }

  private function _validate_item($sales_id, $channel_id, $key)
  {
    $data = $this->mguarantee->valid_item($sales_id, $channel_id, $key);
    return $data;
  }

  private function _validate_item_level2($user_id, $channel_id, $iccid)
  {
    return $this->mguarantee->validate_level_2($user_id, $channel_id, $iccid);
  }

  public function partners()
  {
    $sales_id = $this->input->post("sales_id");
    $user_group_id = $this->input->post("user_group_id");
    $keyword = strtoupper( trim($this->input->post("key")) );
    $data = $this->mguarantee->get_partner($sales_id, $user_group_id, $keyword);
    echo json_encode($data);
  }

  public function frontliner($outlet_id)
  {
    $data = $this->mguarantee->get_frontliners($outlet_id);
    echo json_encode($data);
  }

  public function validate($partner_id) 
  {
    $data = $this->mguarantee->validate($partner_id);
    echo json_encode($data);
  }

  public function validate_item()
  {
    $sales_id = explode(';', $this->input->post("sales_id") );
    $iccid = $this->input->post("keyword");
    $channel_id = $this->input->post("channel_id");
    $data = $this->mguarantee->valid_item($sales_id[0], $channel_id, $iccid);
    // print_r($data);
    echo json_encode($data);
  }

  public function detail($id)
  {
    $template = "shell/smooth";
    $data["main_view"] = "f-claim-detail";
    $data["claim"] = $this->mguarantee->detail($id);
    // print_r($data);
    $this->load->view($template, $data, FALSE);
  }

}

/* End of file guarantee.php */
/* Location: ./application/controllers/guarantee.php */
